import {
		uploadImage
	} from '@/utils/upload';
	export const prodMix = {
		data() {
			return {
				key: 1,
				productList: [],
			}
		},
		methods: {

			// 验证
			//纯数字
			pureNumber(value) {
				if (!/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(value)) {
					return true
				} else {
					return false
				}

			},

			// 上传
			onUploadImage(name) {
				uploadImage().then(res => {
					if (name) { //单个图片
						this.form[name] = res[0]
						return
					}
					this.addKey(res)
				})
			},

			// 删除图片
			onDelete(index, name) {
				if (name) {
					this.form[name] = ''
					return
				}
				this.productList.splice(index, 1)
				this.form.img = this.productList.reduce((pre, el) => {
					pre.push(el.image)
					return pre
				}, []).join(',')

			},


			// 动态修改标题
			dynamic(title) {
				uni.setNavigationBarTitle({
					title
				})
			},

			// 表单验证
			checkInput() {
				let $this = this
				return new Promise((resolve, reject) => {
					let judeg = true
					let judeg2 = true //如果有一个发生错误就终止循环
					for (let i in $this.checkInputList) {
						if (!judeg2) {
							return
						}
						if (judeg) {
							let method = $this.checkInputList[i].method
							if (method && $this[method](this.form[i])) {
								judeg = false
								judeg2 = false
								$this.$toast($this.checkInputList[i].message)
							} else if (!$this.form[i] && $this.form[i] != '0') {
								console.log($this.form['name'])
								judeg = false
								judeg2 = false
								$this.$toast($this.checkInputList[i].message)

							}


						}
					}
					resolve(judeg)
				})
			},

			//编辑或新增成功后调用的方法
			onSuccess(title) {
				this.$hide()
				this.$toast(title)
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 1000)
			},


			//为图片添加key
			addKey(item) {
				if (!Array.isArray(item)) return
				let productList = item.reduce((pre, el) => {
					pre.push({
						image: el,
						key: this.key += 1
					})
					return pre
				}, [])
				if (!this.productList[0]) {
					this.productList = productList
				} else {
					this.productList = this.productList.concat(productList)
				}
				this.form.img = this.productList.map(el => { //转换格式
					return el.image
				}).join(',')
			},

		}
	}
